package com.sencorsta.ids.pos;

import com.sencorsta.ids.core.configure.SysConfig;
import com.sencorsta.ids.core.log.Out;
import com.sencorsta.ids.core.tcp.opensocket.OpenUser;
import com.sencorsta.utils.date.DateUtil;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;

import java.net.InetSocketAddress;
import java.util.concurrent.TimeUnit;

import static java.lang.System.arraycopy;

public class PosSim {
    private String serverIp = "114.80.218.48";
    private int serverPort = 18813;
    private Bootstrap bootstrap;
    private EventLoopGroup group;

    private static final EventLoopGroup m_loop = new NioEventLoopGroup();

    public PosSim(ChannelInitializer<SocketChannel> factory) {
        this(factory, m_loop);
    }

    protected PosSim(ChannelInitializer<SocketChannel> factory, EventLoopGroup loop) {
        group = new NioEventLoopGroup();
        bootstrap = new Bootstrap();
        bootstrap.channel(NioSocketChannel.class);
        bootstrap.option(ChannelOption.TCP_NODELAY, true);
        bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
        bootstrap.handler(factory);
        bootstrap.group(loop);

        // channelFuture = bootstrap.connect(serverIp, serverPort).sync();
    }

    public Channel connect(String host, int port) {
        try {
            this.serverIp = host;
            this.serverPort = port;
            ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));
            future.awaitUninterruptibly(10, TimeUnit.SECONDS);
            if (!future.isSuccess()) {
                if (future.cause() != null) {
                    Out.trace("连接服务器出错:", future.cause().getMessage());
                }
                return null;
            }
            return future.channel();
        } catch (Exception e) {
            Out.error("连接服务器出错", "host:", host, " port:", port + " -> " + e.getMessage());
            //e.printStackTrace();
            return null;
        }
    }


    public void close(Channel channel) throws InterruptedException {
        Out.trace("开始关闭链接");
        channel.closeFuture().sync();
        group.shutdownGracefully();
        Out.trace("关闭链接");
    }
    public static AttributeKey<ICe8583Ans> ans=AttributeKey.valueOf("ANS");
    public static void main(String[] args) throws InterruptedException {
        SysConfig.getInstance().init();
        Out.trace("检查配置");

        String hex = Integer.toHexString(255);
        Out.trace(hex);
        byte ii = (byte) Integer.parseInt("7c", 16);
        Out.trace(ii);
        PosSim client = new PosSim(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline pipeline = ch.pipeline();
                pipeline.addLast("decoder", new PosDecoder());
                pipeline.addLast("encoder", new PosEncoder());
                pipeline.addLast("handler", new PosSimHandler());
            }
        });

        Channel channel = client.connect("114.80.218.48", 18813);


        while (!channel.isActive()) {

        }

        {
            //签到包
            ICe8583Ans myans = new ICe8583Ans();
            byte[] send = new byte[myans.pack.txLen];
            System.out.println("->签到包 demo");
            myans.frame8583QD(myans.fieldsSend, myans.pack);
            //打印出待发送的报文
            send = new byte[myans.pack.txLen];
            arraycopy(myans.pack.txBuffer, 0, send, 0, myans.pack.txLen);
            PosMassage msg = new PosMassage();
            msg.arr = send;
            channel.attr(ans).set(myans);
            channel.writeAndFlush(msg);
        }


//        byte[] send = new byte[myans.pack.txLen];
//        int money = 10; //1分
//        String time= DateUtil.getTime("HHmmss");
//        String date= DateUtil.getTime("yyMMdd");
//        myans.frame8583QRWX(money,time,date,myans.fieldsSend, myans.pack);
//        //打印出待发送的报文
//        send = new byte[myans.pack.txLen];
//        arraycopy(myans.pack.txBuffer, 0, send, 0, myans.pack.txLen);
//
//        PosMassage msg = new PosMassage();
//        msg.arr = send;
//        channel.writeAndFlush(msg);



        //JSONArray jarr= JSON.parseArray("[\"00\",\"c3\",\"60\",\"02\",\"01\",\"00\",\"00\",\"60\",\"02\",\"00\",\"00\",\"00\",\"00\",\"02\",\"00\",\"30\",\"20\",\"04\",\"80\",\"00\",\"c0\",\"80\",\"1d\",\"30\",\"00\",\"00\",\"00\",\"00\",\"00\",\"00\",\"00\",\"10\",\"00\",\"01\",\"46\",\"03\",\"00\",\"99\",\"30\",\"30\",\"30\",\"30\",\"30\",\"30\",\"30\",\"31\",\"39\",\"35\",\"32\",\"37\",\"31\",\"38\",\"31\",\"35\",\"32\",\"30\",\"33\",\"32\",\"34\",\"39\",\"35\",\"31\",\"35\",\"36\",\"00\",\"19\",\"02\",\"00\",\"00\",\"01\",\"00\",\"06\",\"00\",\"00\",\"00\",\"00\",\"00\",\"16\",\"00\",\"00\",\"01\",\"00\",\"01\",\"45\",\"08\",\"07\",\"01\",\"01\",\"5f\",\"01\",\"23\",\"77\",\"65\",\"69\",\"78\",\"69\",\"6e\",\"3a\",\"2f\",\"2f\",\"77\",\"78\",\"70\",\"61\",\"79\",\"2f\",\"62\",\"69\",\"7a\",\"70\",\"61\",\"79\",\"75\",\"72\",\"6c\",\"3f\",\"70\",\"72\",\"3d\",\"55\",\"32\",\"79\",\"63\",\"52\",\"55\",\"4b\",\"5f\",\"02\",\"08\",\"5a\",\"53\",\"57\",\"45\",\"43\",\"48\",\"41\",\"54\",\"5f\",\"03\",\"06\",\"32\",\"30\",\"35\",\"31\",\"34\",\"38\",\"5f\",\"04\",\"06\",\"31\",\"39\",\"30\",\"38\",\"30\",\"37\",\"5c\",\"02\",\"30\",\"34\",\"5f\",\"12\",\"1b\",\"50\",\"41\",\"30\",\"30\",\"39\",\"32\",\"30\",\"31\",\"39\",\"30\",\"38\",\"30\",\"37\",\"32\",\"30\",\"35\",\"31\",\"35\",\"35\",\"37\",\"37\",\"31\",\"35\",\"37\",\"32\",\"33\",\"39\",\"32\",\"42\",\"31\",\"46\",\"46\",\"30\",\"44\",\"46\"]");
        //JSONArray jarr= JSON.parseArray("[\"00\",\"c3\",\"60\",\"02\",\"01\",\"00\",\"00\",\"60\",\"02\",\"00\",\"00\",\"00\",\"00\",\"02\",\"00\",\"30\",\"20\",\"04\",\"80\",\"00\",\"c0\",\"80\",\"1d\",\"30\",\"00\",\"00\",\"00\",\"00\",\"00\",\"00\",\"00\",\"10\",\"00\",\"01\",\"46\",\"03\",\"00\",\"99\",\"30\",\"30\",\"30\",\"30\",\"30\",\"30\",\"30\",\"31\",\"39\",\"35\",\"32\",\"37\",\"31\",\"38\",\"31\",\"35\",\"32\",\"30\",\"33\",\"32\",\"34\",\"39\",\"35\",\"31\",\"35\",\"36\",\"00\",\"19\",\"02\",\"00\",\"00\",\"01\",\"00\",\"06\",\"00\",\"00\",\"00\",\"00\",\"00\",\"16\",\"00\",\"00\",\"01\",\"00\",\"01\",\"45\",\"08\",\"07\",\"01\",\"01\",\"5f\",\"01\",\"23\",\"77\",\"65\",\"69\",\"78\",\"69\",\"6e\",\"3a\",\"2f\",\"2f\",\"77\",\"78\",\"70\",\"61\",\"79\",\"2f\",\"62\",\"69\",\"7a\",\"70\",\"61\",\"79\",\"75\",\"72\",\"6c\",\"3f\",\"70\",\"72\",\"3d\",\"55\",\"32\",\"79\",\"63\",\"52\",\"55\",\"4b\",\"5f\",\"02\",\"08\",\"5a\",\"53\",\"57\",\"45\",\"43\",\"48\",\"41\",\"54\",\"5f\",\"03\",\"06\",\"32\",\"30\",\"35\",\"31\",\"34\",\"38\",\"5f\",\"04\",\"06\",\"31\",\"39\",\"30\",\"38\",\"30\",\"37\",\"5c\",\"02\",\"30\",\"34\",\"5f\",\"12\",\"1b\",\"50\",\"41\",\"30\",\"30\",\"39\",\"32\",\"30\",\"31\",\"39\",\"30\",\"38\",\"30\",\"37\",\"32\",\"30\",\"35\",\"31\",\"35\",\"35\",\"37\",\"37\",\"31\",\"35\",\"37\",\"32\",\"33\",\"39\",\"32\",\"42\",\"31\",\"46\",\"46\",\"30\",\"44\",\"46\"]");

//        byte[] test=new byte[jarr.size()];
//        for (int i = 0; i < test.length; i++) {
//            test[i]= (byte) Integer.parseInt(jarr.getString(i),16);
//        }

        //String request = "007c600201000060020000000002003020048000c08015000000000000012345000127030099303030303030303139353237313831353230333234393531353600192600000100060000000000405f0104303030305f02085a535745434841545f03063136303733325f04063139303831335c0230333239636538343438";
        //String request = "00c3600201000060020000000002003020048000c0801d30000000000000001000014603009930303030303030313935323731383135323033323439353135360019020000010006000000000016000001000145080701015f012377656978696e3a2f2f77787061792f62697a70617975726c3f70723d5532796352554b5f02085a535745434841545f03063230353134385f04063139303830375c0230345f121b5041303039323031393038303732303531353537373135373233393242314646304446";
        //String request = "007c600201000060020000000002003020048000c08015000000000000012345000127030099303030303030303139353237313831353230333234393531353600192600000100060000000000405f0104303030305f02085a535745434841545f03063139303134395f04063139303830375c0230334238363346334543";
        //String request = "00c3600201000060020000000002003020048000c0801d30000000000001234500012803009930303030303030313935323731383135323033323439353135360019020000010006000000000016000001000127080701015f012377656978696e3a2f2f77787061792f62697a70617975726c3f70723d4e4c7a664967375f02085a535745434841545f03063139303134395f04063139303830375c0230345f121b5041303039323031393038303731393031353334313239353734333834343746443435";


//        byte[] recv = My8583Ans.hexStringToBytes(request);
//        // mypack.ans8583Fields(bt,bt.length,mypack.fieldsRecv);
//        //解析
//        Out.trace("开始解析...");
//        My8583Ans myans = new My8583Ans();
//        int ret = myans.ans8583QD(recv,recv.length);
//        if(ret == 0){
//            //打印出解析成功的各个域
//            Out.trace("解析成功!");
//            Out.trace(myans.getFields(myans.fieldsRecv));
//        }


        //Out.trace(request.substring(2, 4));
        //byte[] requestArr = HexStreamToByteArr(request);
       // byte[] findInfoArr = HexStreamToByteArr(findInfo);

//        String time= DateUtil.getTime("HHmmss");
//        Out.trace(time);
//        byte[] timeArr=time.getBytes(Charset.forName("UTF-8"));
//        //Out.trace(Arrays.toString(timeArr));
//        for (int i = 0; i < timeArr.length; i++) {
//            //Out.trace(Integer.toHexString(timeArr[i]));
//            test[99+i]=timeArr[i];
//        }
//
//        String date= DateUtil.getTime("yyMMdd");
//        Out.trace(date);
//        byte[] dateArr=date.getBytes(Charset.forName("UTF-8"));
//        //Out.trace(Arrays.toString(timeArr));
//        for (int i = 0; i < dateArr.length; i++) {
//            //Out.trace(Integer.toHexString(dateArr[i]));
//            test[108+i]=dateArr[i];
//        }
//
//        String rad= "1234567A";
//        byte[] radArr=rad.getBytes(Charset.forName("UTF-8"));
//        for (int i = 0; i < radArr.length; i++) {
//            //Out.trace(Integer.toHexString(dateArr[i]));
//            test[116+i]= radArr[i];
//        }


//        test[96]=(byte) Integer.parseInt(DateUtil.getTime("HH"),16);
//        test[97]=(byte) Integer.parseInt(DateUtil.getTime("HH"),16);
//        test[98]=(byte) Integer.parseInt(DateUtil.getTime("HH"),16);
//        PosMassage msg = new PosMassage();
//        msg.arr = requestArr;
//        channel.writeAndFlush(msg);

//        FunctionSystem.addDelayJob(() -> {
//            PosMassage msg2 = new PosMassage();
//            msg2.arr = findInfoArr;
//            channel.writeAndFlush(msg2);
//        }, 5, TimeUnit.SECONDS);



//        {
//            OpenMessage om = new OpenMessage();
//            om.method = "proxy.ConnectByJson";
//
//            JSONObject json = new JSONObject();
//
//            json.put("123123", "123123");
//
//            om.data = json.toJSONString().getBytes(GlobalConfigure.UTF_8);
//            om.serializeType = TypeSerialize.TYPE_JSON;
//            om.header.type = TypeProtocol.TYPE_REQ;
//            channel.writeAndFlush(om);
//        }
//
//
//        FunctionSystem.addScheduleJob(()->{
//            OpenMessage om=new OpenMessage();
//            om.method="AppTemp.testApp";
//
//            JSONObject json=new JSONObject();
//
//            json.put("123123","123123");
//
//            om.data=json.toJSONString().getBytes(GlobalConfigure.UTF_8);
//            om.serializeType= TypeSerialize.TYPE_JSON;
//            om.header.type= TypeProtocol.TYPE_REQ;
//            channel.writeAndFlush(om);
//        },1,1, TimeUnit.SECONDS);

    }


    public static byte[] HexStreamToByteArr(String hex) {
        byte[] res = new byte[hex.length() / 2];

        for (int i = 0; i < hex.length() / 2; i++) {
            res[i] = (byte) Integer.parseInt(hex.substring(i * 2, i * 2 + 2), 16);
        }
        return res;
    }
}
